package com.ksyzt.ksite2.client.column;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.ksyzt.gwt.client.common.GwtUtil;
import com.ksyzt.gwt.client.common.SysResource;
import com.ksyzt.gwt.client.event.HasMessageHandlers;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.gwt.client.event.MessageHandler;
import com.ksyzt.ksite2.client.common.ServerProxy;
import com.ksyzt.ksite2.shared.modle.COLUMNObj;
import com.ksyzt.ksite2.shared.modle.COLUMNObjs;

public class ColumnTree extends Tree implements HasMessageHandlers {
	private SelectionHandler<TreeItem> m_selection_handler = new SelectionHandler<TreeItem>() {

		public void onSelection(SelectionEvent<TreeItem> event) {

			TreeItem it = event.getSelectedItem();
			if (it.getUserObject() == null) {
				MessageEvent e = new MessageEvent(MessageEvent.CREATEROOT, null);
				fireEvent(e);
			} else {
				MessageEvent e = new MessageEvent(MessageEvent.ITEMCLICK, it);
				fireEvent(e);
			}
		}
	};

	public ColumnTree() {
		super();
		this.addSelectionHandler(m_selection_handler);
	}

	private AsyncCallback<COLUMNObjs> on_root_data = new AsyncCallback<COLUMNObjs>() {

		public void onSuccess(COLUMNObjs result) {

			m_map.clear();
			parseRoot(result);
		}

		public void onFailure(Throwable caught) {

			Window.alert(caught.getMessage());
		}
	};

	private void parseRoot(COLUMNObjs result) {

		if (result.size() > 0) {
			for (int i = 0; i < result.size(); i++) {
				COLUMNObj o = result.get(i);

				TreeItem item = toTreeItem(null, o);
				m_map.put(o.getID(), item);
				item.setState(true);
				getChildItem(item, o);

			}
			// this.setSelectedItem(this.getItem(0), false);
		}

		if (m_bCreate == true) {
			if (result.size() == 0) {
				// 没有跟组织信息 需要创建一个
				this.add(new Label("创建" + m_orgtypename));
			} else {
				if (m_onlyone == false) {
					// 允许创建多个跟组织
					this.add(new Label("创建另一个" + m_orgtypename));
				}
			}
		}
	}

	private void getChildItem(TreeItem item, COLUMNObj o) {
		ServerProxy.SYS_MANAGER
				.getAllColumnChildrens(o.getID(), on_all_chidren);
	}

	private AsyncCallback<COLUMNObjs> on_all_chidren = new AsyncCallback<COLUMNObjs>() {

		public void onSuccess(COLUMNObjs result) {

			// GWT.log("on_all_child:" + result);
			for (int i = 0; i < result.size(); i++) {
				COLUMNObj o = result.get(i);
				TreeItem p = m_map.get(o.getPID());
				if (p != null) {
					TreeItem it = toTreeItem(p, o);

					m_map.put(o.getID(), it);
					//p.setState(true);
				}
			}
		}

		public void onFailure(Throwable caught) {
			messsage(caught.getMessage());
		}
	};

	public void messsage(String text) {
		MessageEvent ev = new MessageEvent(MessageEvent.MESSAGE, text);
		fireEvent(ev);
	}

	private TreeItem toTreeItem(TreeItem p, COLUMNObj o) {
		String content = "";
		String icon = "";
		switch (o.getCOLUMNTYPE()) {
		case ColumnType.CT_CATALOG:
			icon = SysResource.INSTANCE.col_catalog().getSafeUri().asString();
			break;
		case ColumnType.CT_LIST:
			icon = SysResource.INSTANCE.col_list().getSafeUri().asString();
			break;
		case ColumnType.CT_PICTURE:
			icon = SysResource.INSTANCE.col_picture().getSafeUri().asString();
			break;
		case ColumnType.CT_VIDEO:
			icon = SysResource.INSTANCE.col_video().getSafeUri().asString();
			break;
		case ColumnType.CT_ARTICLE:
			icon = SysResource.INSTANCE.col_article().getSafeUri().asString();
			break;
		}
		String typeicon = "<img border='0'  width='16' height='16' src='"
				+ icon + "'/>";
		content = typeicon;

		if (o.getICON() != null && o.getICON().length() > 0) {
			content += "<img border='0'  width='16' height='16' src='"
					+ GWT.getModuleBaseURL() + "../" +ColumnEditor.strImagepath+"/"+GwtUtil.int2path(o.getID())+  "16.jpg'/>";
		}

		content += "<span>" + o.getNAME() + "</span>";

		TreeItem it;
		if (p == null) {
			it = this.addItem(SafeHtmlUtils.fromTrustedString(content));
		} else {
			it = p.addItem(SafeHtmlUtils.fromTrustedString(content));
		}
		it.setUserObject(o);

		return it;
	}

	public TreeItem getTreeItem(int oid) {
		return m_map.get(oid);
	}

	Map<Integer, TreeItem> m_map = new HashMap<Integer, TreeItem>();
	int m_shopmallid = 0;
	int m_orgtype = 0;
	boolean m_onlyone = true;
	String m_orgtypename = "";

	/**
	 * 初始化组织树
	 * 
	 * @param userid
	 *            该组织树所属用户ID
	 * @param orgtype
	 *            要编辑的组织类型ID
	 * @param orgtypename
	 *            组织类型名称
	 * @param onlyone
	 *            是否只能创建一个跟组织
	 */
	public void initTree(int shopmallid, int orgtype, String orgtypename,
			boolean onlyone) {
		this.clear();
		m_shopmallid = shopmallid;
		m_orgtype = orgtype;
		m_onlyone = onlyone;
		m_orgtypename = orgtypename;

		ServerProxy.SYS_MANAGER.getColumns(m_shopmallid, m_orgtype,
				on_root_data);
	}

	boolean m_bCreate = true;

	public void EnableCreate(boolean b) {
		m_bCreate = b;
	}

	public HandlerRegistration addMessageHandler(MessageHandler handler) {

		return this.addHandler(handler, MessageEvent.TYPE);
	}
}
